import React, { useState } from "react";
import {
  Button,
  Card,
  Typography,
  Form,
  Input,
  Upload,
  Select,
  Radio,
  Space,
  message,
  Alert,
  Divider,
  Tag,
  List,
  Progress,
  Tooltip,
} from "antd";
import {
  InboxOutlined,
  FileOutlined,
  SettingOutlined,
  DeleteOutlined,
  FileTextOutlined,
  FileImageOutlined,
  FilePdfOutlined,
  FileExcelOutlined,
  FileWordOutlined,
  FileZipOutlined,
  FileUnknownOutlined,
  CheckCircleOutlined,
} from "@ant-design/icons";
import type { UploadFile, UploadProps } from "antd/es/upload/interface";
import SteppedModal from "../components/SteppedModal";
import type { StepConfig } from "../components/SteppedModal";
import "./styles/FileUploadDemo.less";

const { Title, Paragraph, Text } = Typography;
const { Dragger } = Upload;
const { Option } = Select;
const { TextArea } = Input;

const FileUploadDemo: React.FC = () => {
  const [visible, setVisible] = useState(false);
  const [uploadForm] = Form.useForm();
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [uploading, setUploading] = useState(false);

  // 上传配置
  const uploadProps: UploadProps = {
    name: "file",
    multiple: true, // 改为支持多文件上传
    fileList,
    showUploadList: false, // 隐藏默认的文件列表
    beforeUpload: (file) => {
      // 检查文件大小 (10MB 限制)
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        message.error("文件大小不能超过 10MB!");
        return Upload.LIST_IGNORE;
      }

      // 添加到文件列表而不是替换
      setFileList((prevList) => [...prevList, file]);
      return false; // 阻止自动上传
    },
    onRemove: (file) => {
      // 从列表中移除指定文件
      setFileList((prevList) =>
        prevList.filter((item) => item.uid !== file.uid)
      );
    },
  };

  // 获取文件图标
  const getFileIcon = (fileType: string) => {
    if (!fileType) return <FileUnknownOutlined className="file-icon" />;

    if (fileType.includes("image"))
      return <FileImageOutlined className="file-icon file-icon-image" />;
    if (fileType.includes("pdf"))
      return <FilePdfOutlined className="file-icon file-icon-pdf" />;
    if (fileType.includes("word") || fileType.includes("document"))
      return <FileWordOutlined className="file-icon file-icon-word" />;
    if (fileType.includes("excel") || fileType.includes("sheet"))
      return <FileExcelOutlined className="file-icon file-icon-excel" />;
    if (
      fileType.includes("zip") ||
      fileType.includes("rar") ||
      fileType.includes("tar")
    )
      return <FileZipOutlined className="file-icon file-icon-zip" />;

    return <FileTextOutlined className="file-icon" />;
  };

  // 格式化文件大小
  const formatFileSize = (sizeInBytes: number) => {
    if (sizeInBytes < 1024) {
      return `${sizeInBytes} B`;
    } else if (sizeInBytes < 1024 * 1024) {
      return `${(sizeInBytes / 1024).toFixed(1)} KB`;
    } else {
      return `${(sizeInBytes / (1024 * 1024)).toFixed(1)} MB`;
    }
  };

  // 自定义文件列表组件
  const CustomFileList = () => {
    if (fileList.length === 0) return null;

    return (
      <div className="file-list-container">
        <div className="file-list-header">
          <div className="file-list-title">已选择 {fileList.length} 个文件</div>
          <Button
            type="text"
            danger
            onClick={() => setFileList([])}
            disabled={uploading}
          >
            清空
          </Button>
        </div>

        <List
          className="file-list"
          itemLayout="horizontal"
          dataSource={fileList}
          renderItem={(file) => (
            <List.Item
              className="file-list-item"
              actions={[
                <Tooltip title="删除" key="delete">
                  <Button
                    type="text"
                    danger
                    icon={<DeleteOutlined />}
                    disabled={uploading}
                    onClick={() => {
                      setFileList((prev) =>
                        prev.filter((item) => item.uid !== file.uid)
                      );
                    }}
                  />
                </Tooltip>,
              ]}
            >
              <div className="file-item-content">
                {getFileIcon(file.type || "")}
                <div className="file-info">
                  <div className="file-name" title={file.name}>
                    {file.name}
                  </div>
                  <div className="file-meta">
                    <span className="file-size">
                      {formatFileSize(file.size || 0)}
                    </span>
                    <span className="file-type">{file.type || "未知类型"}</span>
                  </div>
                </div>
              </div>
            </List.Item>
          )}
        />
      </div>
    );
  };

  // 两个步骤的配置
  const steps: StepConfig[] = [
    {
      title: "选择文件",
      content: (
        <Form form={uploadForm} layout="vertical">
          <Form.Item
            name="files"
            rules={[{ required: true, message: "请选择要上传的文件" }]}
            style={{ marginBottom: 16 }}
          >
            <Dragger {...uploadProps} className="file-upload-dragger">
              <p className="ant-upload-drag-icon">
                <InboxOutlined />
              </p>
              <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
              <p className="ant-upload-hint">
                支持批量上传多个文件，单个文件大小不超过 10MB
              </p>
            </Dragger>
          </Form.Item>

          {/* 自定义文件列表 */}
          <CustomFileList />
        </Form>
      ),
      // 如果没有选择文件，禁用下一步按钮
      nextDisabled: fileList.length === 0,
    },
    {
      title: "参数设置",
      content: (
        <Form
          form={uploadForm}
          layout="vertical"
          initialValues={{
            accessLevel: "public",
            category: "document",
          }}
        >
          <Alert
            message={`批量设置 ${fileList.length} 个文件的通用参数`}
            description="以下参数将应用于所有选中的文件"
            type="info"
            showIcon
            style={{ marginBottom: 16 }}
          />

          <Form.Item name="batchFilename" label="批量重命名前缀">
            <Input placeholder="可选，用于批量重命名文件的前缀，如：项目文档_" />
          </Form.Item>

          <Form.Item name="description" label="文件描述">
            <TextArea placeholder="请输入文件描述信息" rows={3} />
          </Form.Item>

          <Form.Item name="category" label="文件分类">
            <Select placeholder="请选择文件分类">
              <Option value="document">文档</Option>
              <Option value="image">图片</Option>
              <Option value="video">视频</Option>
              <Option value="audio">音频</Option>
              <Option value="other">其他</Option>
            </Select>
          </Form.Item>

          <Form.Item name="tags" label="标签">
            <Select
              mode="tags"
              placeholder="输入标签并按回车"
              style={{ width: "100%" }}
            />
          </Form.Item>

          <Form.Item name="accessLevel" label="访问权限">
            <Radio.Group>
              <Space direction="vertical">
                <Radio value="public">
                  <Text>公开</Text>
                  <Text type="secondary" style={{ marginLeft: 8 }}>
                    所有人可见
                  </Text>
                </Radio>
                <Radio value="internal">
                  <Text>内部</Text>
                  <Text type="secondary" style={{ marginLeft: 8 }}>
                    仅组织内部成员可见
                  </Text>
                </Radio>
                <Radio value="private">
                  <Text>私密</Text>
                  <Text type="secondary" style={{ marginLeft: 8 }}>
                    仅自己可见
                  </Text>
                </Radio>
              </Space>
            </Radio.Group>
          </Form.Item>
        </Form>
      ),
    },
  ];

  // 处理步骤切换
  const handleStepChange = (current: number, next: number) => {
    // 第一步到第二步：验证是否已选择文件
    if (current === 0 && next === 1) {
      if (fileList.length === 0) {
        message.error("请先选择要上传的文件");
        return false;
      }
      return true;
    }
    return true;
  };

  // 打开对话框
  const showModal = () => {
    setVisible(true);
    setFileList([]);
    uploadForm.resetFields();
  };

  // 关闭对话框
  const handleCancel = () => {
    setVisible(false);
    setFileList([]);
  };

  // 处理上传完成
  const handleFinish = async () => {
    try {
      // 验证表单
      await uploadForm.validateFields();

      // 模拟上传
      setUploading(true);

      // 获取表单数据
      const values = uploadForm.getFieldsValue();

      // 创建FormData对象
      const formData = new FormData();
      fileList.forEach((file, index) => {
        // 对每个文件使用不同的名称
        formData.append(`file-${index}`, file as any);
      });

      // 添加文件数量信息
      formData.append("fileCount", fileList.length.toString());

      // 添加其他参数
      Object.keys(values).forEach((key) => {
        if (key !== "files" && values[key] !== undefined) {
          if (key === "tags" && Array.isArray(values[key])) {
            formData.append(key, JSON.stringify(values[key]));
          } else {
            formData.append(key, values[key]);
          }
        }
      });

      // 模拟API请求
      setTimeout(() => {
        setUploading(false);
        message.success(`成功上传 ${fileList.length} 个文件！`);
        console.log("上传数据:", {
          files: fileList,
          params: values,
        });
        setVisible(false);
      }, 1500);
    } catch (error) {
      console.error("表单验证失败:", error);
    }
  };

  return (
    <div className="file-upload-demo">
      <Title level={2}>文件上传</Title>
      <Paragraph>
        使用步骤式对话框实现的文件上传功能，分为选择文件和设置参数两个步骤。
      </Paragraph>

      <Card className="demo-card">
        <Space direction="vertical" size="large" style={{ width: "100%" }}>
          <div>
            <Title level={4}>文件上传示例</Title>
            <Paragraph>
              这个示例演示了如何使用步骤式对话框组件来实现文件上传流程，包括文件选择和参数设置两个步骤。
            </Paragraph>
            <Button type="primary" onClick={showModal}>
              上传文件
            </Button>
          </div>

          <Divider />

          <div>
            <Title level={5}>支持的功能</Title>
            <Space size={[8, 16]} wrap>
              <Tag color="blue">文件选择</Tag>
              <Tag color="green">文件预览</Tag>
              <Tag color="purple">参数设置</Tag>
              <Tag color="orange">权限控制</Tag>
              <Tag color="cyan">标签分类</Tag>
            </Space>
          </div>
        </Space>
      </Card>

      {/* 文件上传对话框 */}
      <SteppedModal
        title="文件上传"
        visible={visible}
        onCancel={handleCancel}
        onFinish={handleFinish}
        steps={steps}
        onStepChange={handleStepChange}
        finishText={uploading ? "上传中..." : "开始上传"}
        nextText="下一步"
        prevText="上一步"
      />
    </div>
  );
};

export default FileUploadDemo;
